/*
 * @Description: actions
 * @Author: Liu Kunpeng
 * @Date: 2021-07-05 20:41:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-09 15:12:47
 */
import { getUserInfoApi } from '@/api/login'
import { getPermissionsMenuApi } from '@/api/roles/roles'
import router from '@/router'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    userinfo:{},
    treePermission:[]
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_USERINFO: (state, userinfo) => {
    state.userinfo = userinfo
  },
  SET_PERMISSION: (state, permission) => {
    state.treePermission = permission
  }
}

const actions = {
  // get user info  获取用户信息
  getUserInfo(context) {
    return new Promise((resolve, reject) => {
      getUserInfoApi().then(response => {
        const data = response.data.user
        if (!data) {
          Message.error('获取用户信息错误，请重新登录')
          router.push('/login')
          return reject('获取用户信息错误，请重新登录')
        }
        context.commit('SET_USERINFO', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  
  //获取树形权限
  getTreePermission(context) {
    return new Promise((resolve, reject) => {
      getPermissionsMenuApi().then(response => {
        const data = response.data.permissionList
        if (!data) {
          Message.error('获取用户信息错误，请重新登录')
          return reject('获取用户信息错误，请重新登录')
        }
        context.commit('SET_PERMISSION', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  resetState(context){
    return context.commit('RESET_STATE')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

